package com.mybase.app.IO_Net;

import android.app.Activity;
import com.lidroid.xutils.http.client.multipart.content.FileBody;
import com.lidroid.xutils.http.client.multipart.content.StringBody;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by happy_000 on 2014/12/5.
 * 使用HttpClient发送请求、接收响应很简单，一般需要如下几步即可。
 1. 创建HttpClient对象。
 2. 创建请求方法的实例，并指定请求URL。如果需要发送GET请求，创建HttpGet对象；如果需要发送POST请求，创建HttpPost对象。
 3. 如果需要发送请求参数，可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数；对于HttpPost对象而言，也可调用setEntity(HttpEntity entity)方法来设置请求参数。
 4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求，该方法返回一个HttpResponse。
 5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头；调用HttpResponse的getEntity()方法可获取HttpEntity对象，该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
 6. 释放连接。无论执行方法是否成功，都必须释放连接
 */

/*********
 * HTTP GET核心代码：

 (1)DefaultHttpClient client = new DefaultHttpClient();
 (2)HttpGet get = new HttpGet(String url);//此处的URL为http://..../path?arg1=value&....argn=value
 (3)HttpResponse response = client.execute(get); //模拟请求
 (4)int code = response.getStatusLine().getStatusCode();//返回响应码
 (5)InputStream in = response.getEntity().getContent();//服务器返回的数据


 HTTP POST核心代码：

 (1)DefaultHttpClient client = new DefaultHttpClient();
 (2)BasicNameValuePair pair = new BasicNameValuePair(String name,String value);//创建一个请求头的字段，比如content-type,text/plain
 (3)UrlEncodedFormEntity entity = new UrlEncodedFormEntity(List<NameValuePair> list,String encoding);//对自定义请求头进行URL编码
 (4)HttpPost post = new HttpPost(String url);//此处的URL为http://..../path
 (5)post.setEntity(entity);
 (6)HttpResponse response = client.execute(post);
 (7)int code = response.getStatusLine().getStatusCode();
 (8)InputStream in = response.getEntity().getContent();//服务器返回的数据
 */
public class HttpClientActivity extends Activity {

    /**
     * post方式提交表单（模拟用户登录请求）
     */
    public void postForm() {

    }

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public void post() {
        // 创建默认的httpClient实例.
        DefaultHttpClient httpclient = new DefaultHttpClient();
        // 创建httppost
        HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("username", "admin"));
        formparams.add(new BasicNameValuePair("password", "123456"));
        formparams.add(new BasicNameValuePair("type", "house"));
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            HttpResponse response = httpclient.execute(httppost);//执行POST方法
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    System.out.println("resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
                    System.out.println("result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //获取响应内容
                }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
//            try {
//                httpclient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
    }

    /**
     * 发送 get请求
     */
    public void get() {


        //先将参数放入List，再对参数进行URL编码  get
        List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("param1", "中国"));
        params.add(new BasicNameValuePair("param2", "value2"));
        //对参数编码
        String param = URLEncodedUtils.format(params, "UTF-8");
        //baseUrl
        String baseUrl = "http://ubs.free4lab.com/php/method.php";
        try {
        //将URL与参数拼接  // 创建httpget.
        HttpGet httpget = new HttpGet(baseUrl + "?" + param);
        DefaultHttpClient httpclient = new DefaultHttpClient();
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            HttpResponse response = httpclient.execute(httpget);//发起GET请求

                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
                    System.out.println("result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//获取服务器响应内容
                    System.out.println("Response content length: " + entity.getContentLength());  // 打印响应内容长度
                    System.out.println("Response content: " + EntityUtils.toString(entity));// 打印响应内容
                }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
//            try {
//                httpclient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
    }

//    /**
//     * 上传文件
//     */
//    public void upload() {
//        DefaultHttpClient httpclient = new DefaultHttpClient();
//        try {
//            HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
//
//            FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
//            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
//
//            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
//            httppost.setEntity(reqEntity);
//
//            System.out.println("executing request " + httppost.getRequestLine());
//            HttpResponse response = httpclient.execute(httppost);
//            try {
//                System.out.println("----------------------------------------");
//                System.out.println(response.getStatusLine());
//                HttpEntity resEntity = response.getEntity();
//                if (resEntity != null) {
//                    System.out.println("Response content length: " + resEntity.getContentLength());
//                }
//                EntityUtils.consume(resEntity);
//            } finally {
//                response.close();
//            }
//        } catch (ClientProtocolException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                httpclient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}


